﻿using Microsoft.Extensions.Logging;
using Syspetro.Core.AppDeal;
using System;

namespace Syspetro.Core.CommandBus
{
    public class CommandBus : ICommandBus
    {
        private readonly IServiceProvider _serviceProvider;
        public CommandBus()
        {
            _serviceProvider = InternalApp.ServicesProvider;
        }

        public SpActionResult Send<T>(T command, params Type[] ignores) where T : Command
        {
            if (command == null)
                return new SpActionResult {  Success = false, Msg = "参数为空" };
            var name = typeof(T).FullName;
            try
            {
                SpActionResult result = new();
                foreach (var handler in CommandMap.Mappings[name])
                {
                    foreach (var ignore in ignores)
                    {
                        if (handler == ignore) { continue; }
                    }
                    var service = _serviceProvider.GetService(handler);
                    if (service == null) return new SpActionResult {  Success = false, Msg = "获取指令失败" };
                    var _service = (ICommandHandler<T>)service;
                    var backedata = _service.Execute(command);
                    result.Success = backedata.Success;
                    result.Add(backedata);
                    if (!result.Success)
                        result.Msg = backedata.Msg;
                }
                return result;
            }
            catch (Exception e)
            {
                string msg = $"Command_{name}错误:{e.Message}";
                return new SpActionResult {  Success = false, Msg = msg };
            }
        }
    }
}
